import { eAccountComponents } from '@abp/ng.account';
import { AuthService, Environment, EnvironmentService } from '@abp/ng.core';
import { ToasterService } from '@abp/ng.theme.shared';
import { Component, Injector, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Store } from '@ngxs/store';
import { OAuthService } from 'angular-oauth2-oidc';
import { Observable, throwError } from 'rxjs';
import { catchError, finalize } from 'rxjs/operators';
import snq from 'snq';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
})
export class LoginComponent implements OnInit {
  form: FormGroup;

  inProgress: boolean;

  isSelfRegistrationEnabled = true;

  authWrapperKey = eAccountComponents.AuthWrapper;

  environment$: Observable<Environment>;

  constructor(
    protected injector: Injector,
    private fb: FormBuilder,
    private oauthService: OAuthService,
    private store: Store,
    private router: Router,
    private toasterService: ToasterService,
    private authService: AuthService,
    private environment: EnvironmentService
  ) {
    this.environment$ = this.environment.getEnvironment$();
  }

  submitForm(): void {
    // tslint:disable-next-line:forin
    for (const i in this.form.controls) {
      this.form.controls[i].markAsDirty();
      this.form.controls[i].updateValueAndValidity();
    }

    const redirectUrl = this.getRedirectUrl(this.injector);

    this.inProgress = true;
    this.authService
      .login({
        username: this.form.get('userName').value,
        password: this.form.get('password').value,
        rememberMe: true,
        redirectUrl,
      })
      .pipe(
        catchError(err => {
          this.toasterService.error(
            snq(() => err.error.error_description) ||
              snq(() => err.error.error.message, 'AbpAccount::DefaultErrorMessage'),
            'Error',
            { life: 7000 }
          );
          return throwError(err);
        }),
        finalize(() => (this.inProgress = false))
      )
      .subscribe(() => {
        //this.router.navigate(['/']);
      });
  }

  ngOnInit(): void {
    this.form = this.fb.group({
      userName: [null, [Validators.required]],
      password: [null, [Validators.required]],
    });
  }

  private getRedirectUrl(injector: Injector) {
    const route = injector.get(ActivatedRoute);
    //const options = injector.get(ACCOUNT_CONFIG_OPTIONS);
    //return route.snapshot.queryParams.returnUrl || options.redirectUrl || '/';
    return route.snapshot.queryParams.returnUrl || '/';
  }
}
